﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using Topshelf;
using Topshelf.Logging;
using WJP;
using WJP.DataPortal.WCF;
using WJP.Logging;

namespace RoutingService
{
    class Program
    {
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += (s, e) =>
            {
                Console.WriteLine(e.ExceptionObject?.ToString());
                LogManager.Logger.Fatal(e.ExceptionObject.ToString());
            };

            HostFactory.Run(x =>
            {
                x.Service<HostService>();
                x.SetDescription(Configuration.ServiceDescription);
                x.SetDisplayName(Configuration.ServiceDisplayName);
                x.SetServiceName(Configuration.ServiceName);
                x.StartAutomaticallyDelayed();
                x.RunAsLocalSystem();
                x.EnableServiceRecovery((e) =>
                {
                    e.RestartService(0);//第一次失败执行
                    e.RestartService(0);//第二次失败执行
                    e.RestartService(0);//后续失败执行

                    e.OnCrashOnly();
                    e.SetResetPeriod(1);
                });
            });
        }
    }

    /// <summary>
    /// 路由服务
    /// </summary>
    public class HostService : ServiceControl
    {
        ServiceHost serviceHost;
        static ILogger logger = NullLogger.Instance;

        public bool Start(HostControl hostControl)
        {
            try
            {
                hostControl.RequestAdditionalTime(TimeSpan.FromSeconds(10));

                DomainApp.Create().Startup();
                logger = LogManager.GetLogger<Program>();

                serviceHost = new ServiceHost(typeof(WJP.DataPortal.WCF.RoutingService));
                serviceHost.Open();

                Console.WriteLine("路由服务启动成功...");

                logger.Info("路由服务启动成功...");
            }
            catch (Exception ex)
            {
                logger.Error("路由服务启动失败：", ex);
            }

            return true;
        }

        public bool Stop(HostControl hostControl)
        {
            serviceHost.Close();
            logger.Info("路由服务停止...");
            return true;
        }
    }
}
